let cols = document.querySelectorAll('.col')
let chess = document.querySelector('.chess')
let msg = document.querySelector('.message')
let message = document.querySelector('.messageContainer') as HTMLDivElement
let toolTip = document.querySelector('h2')
let btn = document.querySelector('button')
let winsArr = [
    [0, 1, 2], [3, 4, 5], [6, 7, 8],
    [0, 3, 6], [1, 4, 7], [2, 5, 8],
    [0, 4, 8], [2, 4, 6]
]
enum Player { X = 'x', O = 'o' }
let currentPlayer: Player
let step: number

function handleClick(e: MouseEvent) {
    let target = e.target as HTMLDivElement
    target.classList.add(currentPlayer)
    // 判断是否已经赢了
    if (isWin(currentPlayer)) {
        toolTip.innerHTML = `玩家 ${currentPlayer} 赢了！！！`
        message.style.display = 'block'
        return
    } else if (step >= 8) {
        toolTip.innerHTML = `这一把平局！！！`
        message.style.display = 'block'
        return
    }
    // 切换玩家
    currentPlayer = currentPlayer === Player.X ? Player.O : Player.X
    // 切换提示
    chess.classList.remove(Player.X, Player.O)
    chess.classList.add(currentPlayer)
    step++
}

function isWin(player: Player) {

    return winsArr.some(item => {
        let flag = 0
        item.forEach(sub => {
            if (cols[sub].classList.contains(player)) {
                flag++
            }
        })
        if (flag === 3) {
            return true
        }
        return false
    })
}

function startGame() {
    // 关闭遮盖层
    message.style.display = 'none'
    // 计数归零
    step = 0
    // 重置玩家
    currentPlayer = Player.X
    // 重置提示
    chess.classList.remove(Player.X, Player.O)
    chess.classList.add(currentPlayer)
    // 对格子的进行初始化操作
    cols.forEach(item => {
        let col = item as HTMLDivElement
        // 移除x, o类
        col.classList.remove(Player.X, Player.O)
        // 解绑上一次的点击事件
        col.removeEventListener('click', handleClick)
        // 重新绑定点击事件
        col.addEventListener('click', handleClick, { once: true })
    })
}

// 开始游戏
startGame()
// 重新开始游戏
btn.addEventListener('click', startGame)

